/*
 * Copyright 2011 www.pretty-tools.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#include "stdafx.h"
#include "DirectoryService.h"


// CDirectoryService

CDirectoryService::CDirectoryService()
{
    ATLTRACE( _T("CDirectoryService::CDirectoryService()\n") );
}

CDirectoryService::~CDirectoryService()
{
    ATLTRACE( _T("CDirectoryService::~CDirectoryService()\n") );
}

STDMETHODIMP CDirectoryService::get(BSTR prop, BSTR iid, VARIANT* pRet)
{
    if (!prop || !*prop || !iid)
        return E_INVALIDARG;
    if (!pRet)
        return E_POINTER;

    ATLTRACE( L"CPrefBranch::get(\"%s\", \"%s\")\n", prop, iid );

    // currently we support only file interface
    if (0 != wcsicmp(L"{F75B5C32-B42D-416D-93AC-8798869674CE}", iid))
        return E_FAIL;

    CComPtr<ISafeLocalFile> file;
    RETURN_FAILED(file.CoCreateInstance(CLSID_LocalFile))

    wchar_t szPath[MAX_PATH+1];
    ZeroMemory(szPath, sizeof(szPath));

    if (0 == wcsicmp(L"ProfD", prop))
    {
        RETURN_FAILED(::SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, szPath))

        if (IsOSVistaOrHigher())
	        wcscat_s(szPath, L"Low");

#ifndef _PROJECT_NAME
#error Please set _PROJECT_NAME to Project Name
#endif
	    wcscat_s(szPath, L"\\");
	    wcscat_s(szPath, _PROJECT_NAME);

	    static bool bCreate = true;
	    if (bCreate) { ::CreateDirectory(szPath, NULL); bCreate = false; }

        RETURN_FAILED(file->Init(CComBSTR(szPath), VARIANT_TRUE))
    }
    else if (0 == wcsicmp(L"TmpD", prop))
    {
	    DWORD dwLength = ::GetTempPath(MAX_PATH, szPath);
        if (!dwLength || dwLength > MAX_PATH)
            return E_FAIL;

        RETURN_FAILED(file->Init(CComBSTR(szPath), VARIANT_TRUE))
    }
    else
    {
        return E_INVALIDARG;
    }

    CComQIPtr<IDispatch> pdisp = file;
    if (pdisp)
        CComVariant((IDispatch*)pdisp).Detach(pRet);
    else
        CComVariant(file).Detach(pRet);

    return S_OK;
}
